package com.powernode.work.service.impl;

import com.powernode.commons.utils.DateUtils;
import com.powernode.commons.utils.ResponseData;
import com.powernode.commons.utils.UUIDUtils;
import com.powernode.work.bean.TranHistoryBean;
import com.powernode.work.dao.TranHistoryMapper;
import com.powernode.work.dao.TranMapper;
import com.powernode.work.service.TranHistoryService;
import com.powernode.work.service.TranService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;

@Service
public class TranHistoryServiceImpl implements TranHistoryService {
    @Autowired
    private TranHistoryMapper dao;

    /**
     * 根据交易的id查询历史记录
     * @param tranId
     * @return
     */
    @Override
    public ResponseData findByTranId(String tranId) {
        return ResponseData.ok(dao.selectByTranId(tranId));
    }

    @Autowired
    private TranMapper tranMapper;
    /**
     * 添加历史阶段
     * 注意: 把当前交易的阶段改成   他的所有的历史阶段中的stage  阶段值最高的阶段
     * @param history
     * @return
     */
    @Override
    @Transactional
    public ResponseData add(TranHistoryBean history) {
        //设置主键
        history.setId(UUIDUtils.getUUID());
        //创建时间
        history.setCreateTime(DateUtils.formatDateTime(new Date()));

        int row = dao.insert(history);
        if (row>0){
            //把当前交易的阶段改成   他的所有的历史阶段中的stage  阶段值最高的阶段
            Map map = dao.selectMaxStageByTranId(history.getTranId());
            tranMapper.updateStageById(history.getTranId(),(String)map.get("maxstage"));

            return ResponseData.ok();
        }
        return ResponseData.error();
    }

    /**
     * 修改历史
     * @param history
     * @return
     */
    @Override
    public ResponseData modify(TranHistoryBean history) {
       int row = dao.updateByPrimaryKeySelective(history);
        if (row>0){
            //把当前交易的阶段改成   他的所有的历史阶段中的stage  阶段值最高的阶段
            Map map = dao.selectMaxStageByTranId(history.getTranId());
            tranMapper.updateStageById(history.getTranId(),(String)map.get("maxstage"));
            return ResponseData.ok();
        }
        return ResponseData.error();
    }
}
